package com.todo.utils;
import com.todo.entity.TID;
import com.todo.mapper.TIDMapper;
import com.todo.mapper.TeamMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class TIDUtil {

    @Resource
    private TeamMapper teamMapper;

    @Resource
    private TIDMapper tidMapper;

    /**
     * 号池起始号码
     */
    private static final Long TID_START_NUMBER = 1000100000L;

    /**
     * 号池每次更新数量
     */
    private static final int TID_ADD_COUNT = 100;

    /**
     * 从号池中获取一个uid
     * @return
     */
    public synchronized String getTID(){
        TID tidObj = tidMapper.getTID();
        //判断号池中是否还有uid号码
        if(tidObj==null){
            //添加uid进入号池
            addTIDs(TID_ADD_COUNT);
            return getTID();
        }
        log.info("获取tid成功:{}",tidObj.getTid());
        int i = tidMapper.deleteById(tidObj.getId());
        if (i<1){
            return getTID();
        }
        log.info("从号池中成功移除uid");
        return tidObj.getTid();

    }
    private void addTIDs(int count){
        if (count<=0){
            log.info("新增号池数量中tid数量不能小于等于0");
            return;
        }
        //1.1查询数据库中总用户数量
        int total = teamMapper.count();
        //1.2添加号池的次数
        int addStart = total / TID_ADD_COUNT;
        //1.3判断用户数量等于卡池中被删除的uid的数量
        //1.3.1获取模UID_ADD_COUNT的余数
        int remainder = total % TID_ADD_COUNT;
        if (remainder>0){
            //有余数，需要将添加uid的起始位加一(第addStart个UID_ADD_COUNT开始)
            addStart = addStart + 1;
        }
        //2.计算添加如UID池的号码范围
        //2.1 用最初开始的号码加总用户数量计算出添加UID的起始号
        long start = TID_START_NUMBER + (long) addStart *TID_ADD_COUNT;

        //2.2 循环插入
        while (count!=0){

            tidMapper.insert(new TID().setTid(Long.toString(start++)));
            count--;
        }
        log.info("添加tid号池成功");
    }
}
